import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { TransferItem } from 'ng-zorro-antd/transfer';
import { BehaviorSubject } from 'rxjs';
import { Consts } from 'src/app/consts/consts';
import { RoleQueryParam } from 'src/app/models/param/role-query.param';
import { UserPermParam } from 'src/app/models/param/user-perm.param';
import { RoleDto } from 'src/app/models/sys/role.dto';
import { UserDto } from 'src/app/models/sys/user.dto';
import { ApiService } from 'src/app/services/api.service';

@Component({
  selector: 'app-assign-roles',
  templateUrl: './assign-roles.component.html',
  styleUrl: './assign-roles.component.less'
})
export class AssignRolesComponent implements OnInit {
  @Input() assignRoleSubject!: BehaviorSubject<UserDto>;
  @Output() assignRoleEvent = new EventEmitter<boolean>();

  user = new UserDto();

  roles: RoleDto[] = [];

  list: {label: string, value: string, checked: boolean}[] = []
  selectedKeys: string[] = ['100', '101'];

  constructor(private _api: ApiService, private _message: NzMessageService) {

  }

  ngOnInit(): void {
    this.assignRoleSubject.subscribe((value) => {
      this._api.getUserDetail(value.userId).subscribe((resp) => {
        if (resp.code == Consts.RESP_OK && resp.data) {
          this.user = resp.data;
          this.toSelectedItems(this.user);

          const param = new RoleQueryParam();

          this._api.getRoleList(param).subscribe((resp) => {
            if (resp.code == Consts.RESP_OK && resp.data) {
              this.roles = resp.data;
              this.toTransferItems(this.roles);
            }
          });
        }
      });
    });

  }

  toTransferItems(roles: RoleDto[]) {
    this.list = [];

    for (const role of roles) {
      if (this.selectedKeys.includes(role.roleId.toString())) {
        console.log(`already selected ${role.roleId}`);
        this.list.push({
          value: role.roleId.toString(),
          label: role.roleName,
          checked: true
        });
      } else {
        this.list.push({
          value: role.roleId.toString(),
          label: role.roleName,
          checked: false
        })
      }
      
      console.log(`has role key ${role.roleId}`);
    }
  }

  toSelectedItems(user: UserDto) {
    this.selectedKeys = [];
    for (const role of user.roles) {
      this.selectedKeys.push(role.roleId.toString());
      console.log(`Already selected: ${role.roleId}`);        
      }
  }

  select(ret: {list: TransferItem[]}): void {
    this.selectedKeys = ret.list.map(x => x['key']);
    console.log('nzSelectChange', ret);
  }

  change(value: object[]) {
    console.log('nzChange', value);
    this.selectedKeys = value.map(x => x.toString());
  }

  onCancel(event: UIEvent) {
    event.preventDefault();
    console.log('onCancel');
    this.assignRoleEvent.emit(false);
  }

  onAssign() {
    if (this.user == null) {
      this._message.warning("用户不存在");
      return
    }

    const roleIds = this.selectedKeys.map(x => Number(x));

    console.log(`Assign roles : ${roleIds.join(",")}`);
    const param = new UserPermParam();
    param.userId = this.user.userId;
    param.roleIds = roleIds;
    this._api.assignRoles(param).subscribe((resp) => {
      if (resp.code == Consts.RESP_OK) {
        this._message.info("Assign OK");
        this.assignRoleEvent.emit(true);
      } else {
        this._message.warning("Assign Error");
      }
    });
  }
}
